package net.seehealth.healthpad.application.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.seehealth.healthpad.Constants;
import net.seehealth.healthpad.dataaccess.HealthSqliteHelper;
import net.seehealth.healthpad.model.weather.WeatherBean;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
 * 
 * @className WeatherService
 * @author 刘绍辉
 * @description TODO 通过天气webservice 获取州，省份，城市，天气信息
 * @date 2012-3-14 上午9:46:24
 */
public class WeatherService {
    /********
     * 获得州，国内外省份和城市信息
     * @return
     */
    public  List<String> getProvince(){
        List<String> provinces=new ArrayList<String>();
        String str="";
        SoapObject soapObject=new SoapObject(Constants.Common.TARGETNAMESPACE,Constants.Common.GETSUPPORTPROVINCE);
        SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet=true;
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE httpTranstation=new HttpTransportSE(Constants.Common.WSDL);
        try {
            
            httpTranstation.call(Constants.Common.TARGETNAMESPACE+Constants.Common.GETSUPPORTPROVINCE, envelope);
            SoapObject result=(SoapObject)envelope.getResponse();
            //下面对结果进行解析，结构类似json对象
            //str=(String) result.getProperty(6).toString();
            
            int count=result.getPropertyCount();
            for(int index=0;index<count;index++){
                provinces.add(result.getProperty(index).toString());
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return provinces;
    }
    
    /**********
     * 根据省份或者直辖市获取天气预报所支持的城市集合
     * @param province
     * @return
     */
    public  List<String> getCitys(String province){
        List<String> citys=new ArrayList<String>();
        SoapObject soapObject=new SoapObject(Constants.Common.TARGETNAMESPACE,Constants.Common.GETSUPPORTCITY);
        soapObject.addProperty("byProvinceName", province);
        SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet=true;
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE httpTransport=new HttpTransportSE(Constants.Common.WSDL);
        try {
            httpTransport.call(Constants.Common.TARGETNAMESPACE+Constants.Common.GETSUPPORTCITY, envelope);
            SoapObject result=(SoapObject)envelope.getResponse();
            int count=result.getPropertyCount();
            for(int index=0;index<count;index++){
            	if(result.getProperty(index)!=null&&!result.getProperty(index).equals("")){
            		citys.add(result.getProperty(index).toString());
            	}
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } 
        return citys;
    }
    
    /***************************
     * 根据城市信息获取天气预报信息
     * @param city
     * @return
     ***************************/
    public  WeatherBean getWeatherByCity(String city){
        
        WeatherBean bean=new WeatherBean();

        SoapObject soapObject=new SoapObject(Constants.Common.TARGETNAMESPACE,Constants.Common.GETWEATHERBYCITYNAME);
        soapObject.addProperty("theCityName",city);//调用的方法参数与参数值（根据具体需要可选可不选）
        
        SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet=true;
        envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
        
        
        //AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
        HttpTransportSE httpTranstation=new HttpTransportSE(Constants.Common.WSDL);
        try {
            httpTranstation.call(Constants.Common.TARGETNAMESPACE+Constants.Common.GETWEATHERBYCITYNAME, envelope);
            SoapObject result=(SoapObject)envelope.getResponse();
            //下面对结果进行解析，结构类似json对象
            bean=parserWeather(result);
             
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return bean;
    }
    
    /**
     * 解析返回的结果
     * @param soapObject
     */
    protected   WeatherBean parserWeather(SoapObject soapObject){
    	WeatherBean bean=new WeatherBean();
    	if(!soapObject.getProperty(1).toString().equals("anyType{}")){
    		 
    	        
    	        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
    	        
    	        
    	        Map<String,Object> map=new HashMap<String,Object>();
    	        
    	        //城市名
    	        bean.setCityName(soapObject.getProperty(1).toString());
    	        //城市简介
    	        bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount()-1).toString());
    	        //天气实况+建议
    	        bean.setLiveWeather(soapObject.getProperty(10).toString()+"\n"+soapObject.getProperty(11).toString());
    	        //其他数据
    	        //日期，
    	        String date=soapObject.getProperty(6).toString();
    	        //---------------------------------------------------
    	        String weatherToday="今天：" + date.split(" ")[0];  
    	        weatherToday+="\n天气："+ date.split(" ")[1]; 
    	        weatherToday+="\n气温："+soapObject.getProperty(5).toString();
    	        weatherToday+="\n风力："+soapObject.getProperty(7).toString();
    	        weatherToday+="\n";
    	           
    	        List<Integer> icons=new ArrayList<Integer>();
    	    
    	        icons.add(parseIcon(soapObject.getProperty(8).toString()));      
    	        icons.add(parseIcon(soapObject.getProperty(9).toString()));
    	         
    	        map.put("weatherDay", weatherToday);
    	        map.put("icons",icons);
    	        list.add(map);
    	        
    	        
    	        

    	        //-------------------------------------------------
    	        map=new HashMap<String,Object>(); 
    	        date=soapObject.getProperty(13).toString();
    	        String weatherTomorrow="明天：" + date.split(" ")[0];  
    	        weatherTomorrow+="\n天气："+ date.split(" ")[1]; 
    	        weatherTomorrow+="\n气温："+soapObject.getProperty(12).toString();
    	        weatherTomorrow+="\n风力："+soapObject.getProperty(14).toString();
    	        weatherTomorrow+="\n";
    	        
    	        icons=new ArrayList<Integer>();
    	         
    	        icons.add(parseIcon(soapObject.getProperty(15).toString()));      
    	        icons.add(parseIcon(soapObject.getProperty(16).toString()));
    	        
    	        map.put("weatherDay", weatherTomorrow);
    	        map.put("icons",icons);
    	        list.add(map);
    	        //--------------------------------------------------------------
    	        map=new HashMap<String,Object>(); 
    	        
    	        date=soapObject.getProperty(18).toString();
    	        String weatherAfterTomorrow="后天：" + date.split(" ")[0];  
    	        weatherAfterTomorrow+="\n天气："+ date.split(" ")[1]; 
    	        weatherAfterTomorrow+="\n气温："+soapObject.getProperty(17).toString();
    	        weatherAfterTomorrow+="\n风力："+soapObject.getProperty(19).toString();
    	        weatherAfterTomorrow+="\n";
    	        
    	        icons=new ArrayList<Integer>();
    	        icons.add(parseIcon(soapObject.getProperty(20).toString()));      
    	        icons.add(parseIcon(soapObject.getProperty(21).toString()));
    	        
    	        map.put("weatherDay", weatherAfterTomorrow);
    	        map.put("icons",icons);
    	        list.add(map); 
    	        //--------------------------------------------------------------
    	        
    	        bean.setList(list);
    	}
       
        return bean;
    }
    
     //解析图标字符串
     private int parseIcon(String data){
        // 0.gif，返回名称0,
         int resID=32;
         String result=data.substring(0, data.length()-4).trim();
          // String []icon=data.split(".");
          // String result=icon[0].trim();
          //   Log.e("this is the icon", result.trim());
          
           if(!result.equals("nothing")){
               resID=Integer.parseInt(result.trim());
           }
         return resID;
         //return ("a_"+data).split(".")[0]; 
     } 
     private void saveProvinceAndCitys(Context context){
    	 List<String> provinces = this.getProvince();
    	 HealthSqliteHelper helper = new HealthSqliteHelper(context);
    	 SQLiteDatabase db = helper.getWritableDatabase();
		 ContentValues values = new ContentValues();
		 for (String pname : provinces) {
			String [] pnames = pname.split(" ");
			values.put("pid", pnames[1]);
			values.put("pname", pnames[0]);
			db.insert("province", null, values);
			values.clear();
			List<String> citys = this.getCitys(pnames[0]);
			for (String cname : citys) {
				String [] cnames = cname.split(" ");
				values.put("cid", cnames[1]);
				values.put("cname", cnames[0]);
				values.put("pid", pnames[1]);
				db.insert("city", null, values);
				values.clear();
			}
		}
		 db.close();
		 helper.close();
     }
     private List<String> getLocalProvinces(Context context){
    	 List<String> provinces = new ArrayList();
    	 HealthSqliteHelper helper = new HealthSqliteHelper(context);
    	 SQLiteDatabase db = helper.getWritableDatabase();
    	 Cursor cursor = db.query("province", new String[]{"pname"}, null, null, null, null, null);
    	 for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {
				provinces.add(cursor.getString(cursor.getColumnIndex("pname")));
		}
		cursor.close();
		db.close();
		helper.close();
		return provinces;
     }
     private List<String> getLocalCitysByProvinceName(Context context,String pname){
    	 List<String> citys = new ArrayList();
    	 HealthSqliteHelper helper = new HealthSqliteHelper(context);
    	 SQLiteDatabase db = helper.getWritableDatabase();
    	 Cursor cursor = db.query("city", new String[]{"cname"}, "pname=?", new String[]{pname}, null, null, null);
    	 for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {
    		 citys.add(cursor.getString(cursor.getColumnIndex("cname")));
    	 }
    	 return citys;
     }
}

